package tk.zater.Util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;

import tk.zater.download;
import tk.zater.CS.Constant;
import tk.zater.CS.EsetVersionConfigeration;
import tk.zater.CS.UserAccountManagermant;


public class FileDownloader {
	EsetVersionConfigeration evc;
	Logger logger = Logger.getLogger(FileDownloader.class);
	
	Constant constant = (Constant) ApplicationGetter.Getbean("LoginInInformation");
	
    public FileDownloader(EsetVersionConfigeration evc) {
		super();
		this.evc = evc;
	}

	public static final int cache = 10 * 1024;

    public  void download(String url, String Filename,String Account[]) {
        try {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            if (UserAccountManagermant.userAccount.size() == 0) {
               logger.error("Error 1012:not enough.全部账户失效");
                return;
            }
            RequestConfig config = null;
            credsProvider.setCredentials(new AuthScope(evc.domain, 80),
                    new UsernamePasswordCredentials(Account[0],Account[1]));
            HttpHost proxy = null;
            if (constant.openproxy) {
                credsProvider.setCredentials(
                        new AuthScope(constant.ip, constant.port),
                        new UsernamePasswordCredentials(constant.proxyusername, constant.proxypassword));
                proxy = new HttpHost(constant.ip, constant.port);
                config = RequestConfig.custom()
                        .setProxy(proxy)
                        .build();
            }

            CloseableHttpClient httpclient = HttpClients.custom().setUserAgent(evc.emulator).setDefaultCredentialsProvider(credsProvider).build();
            HttpHost target = new HttpHost(evc.domain, 80, "http");
            HttpGet httpget = new HttpGet(url);
            if(constant.openproxy){
             httpget.setConfig(config);
            
            }
            CloseableHttpResponse response = httpclient.execute(target, httpget);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            File file = new File(Filename);
            FileOutputStream fileout = new FileOutputStream(file);

            byte[] buffer = new byte[cache];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  void download(String url,String Account[]) {
        download(url, path(url),Account);
    }

    public String path(String url) {
        String[] urlsp = url.split("/");
        StringBuffer buffer = new StringBuffer(evc.absolutePath);
        buffer.append(urlsp[urlsp.length - 1]);
        return buffer.toString();
    }

}
